package com.example.mqtt.client;

import com.example.mqtt.config.MqttProperties;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
 * 发送消息客户端的方法
 * 订阅主题的client和发送消息的client，可以是同一个client
 */
@Slf4j
@Component
public class MqttSendClient {
    @Autowired
    private MqttClient sendMqttClient;
    @Autowired
    private MqttProperties mqttProperties;

    /**
     * 发布
     */
    public void publish(String pushMessage) {
        publish(0, false, mqttProperties.getDefaultTopic(), pushMessage);
    }

    /**
     * 发布，默认qos为0，非持久化
     *
     * @param topic 主题名
     * @param pushMessage 消息
     */
    public void publish(String topic, String pushMessage) {
        publish(0, false, topic, pushMessage);
    }

    /**
     * 发布
     *
     * @param qos
     * @param retained
     * @param topic
     * @param pushMessage
     */
    public void publish(int qos, boolean retained, String topic, String pushMessage) {
        MqttMessage message = new MqttMessage();
        message.setQos(qos);
        message.setRetained(retained);
        message.setPayload(pushMessage.getBytes());
        MqttTopic mTopic = sendMqttClient.getTopic(topic);
        if (null == mTopic) {
            log.error("主题不存在:{}",mTopic);
        }
        try {
            mTopic.publish(message);
            log.info("消息发送成功");
        } catch (Exception e) {
            log.error("mqtt发送消息异常:",e);
        }
    }

    /**
     * 重新连接
     */
    public void reConnection() {
        try {
            sendMqttClient.connect();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭连接
     *
     * @param mqttClient
     */
    public static void disconnect(MqttClient mqttClient) {
        try {
            if (mqttClient != null) mqttClient.disconnect();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    /**
     * 释放资源
     *
     * @param mqttClient
     */
    public static void close(MqttClient mqttClient) {
        try {
            if (mqttClient != null) mqttClient.close();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
}
